package com.haoshuang.zhouzhoubang.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ImageUtils
import com.haoshuang.zhouzhoubang.databinding.ActivitySetExtraCostsBinding
import com.haoshuang.zhouzhoubang.ui.adapter.ChooseImageAdapter
import com.haoshuang.zhouzhoubang.ui.vm.SetExtraCostsViewModel
import com.haoshuang.zhouzhoubang.utils.MultiMediaChooseUtils
import com.haoshuang.zhouzhoubang.utils.OSSUploadUtils
import com.haoshuang.zhouzhoubang.widget.UploadFileBean
import com.luck.picture.lib.entity.LocalMedia
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.convertDouble
import com.mufeng.libs.utils.ktx.convertInt
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.isBold
import com.mufeng.libs.utils.view.visibleOrGone


/**
 *  设置额外费用
 */
class SetExtraCostsActivity :
    BaseVMActivity<SetExtraCostsViewModel, ActivitySetExtraCostsBinding>() {

    companion object {
        fun launch(context: Context, order_id: Int?, type: Int) {
            context.startPage<SetExtraCostsActivity>("order_id" to order_id, "type" to type)
        }
    }

    // 订单id
    private var order_id = 0
    // 0 返回数据给上一页, 否则调用接口
    private var type = 0

    private var index = 0

    private var name = ""
    private var price = ""
    private var cost_id: Int? = null
    private var remark = ""
    // 图片
    private var cost_img = ""


    override fun initIntent() {
        order_id = intent.getIntExtra("order_id", 0)
        type = intent.getIntExtra("type", 0)

        // 2 填写 1: 选择
        val cost_status = intent.getIntExtra("cost_status", 2)
        index = if (cost_status == 2) 0 else 1
        // 费用名字
        name = intent.getString("cost_name")
        // 费用
        price = intent.getString("money")
        // 费用id
        if (cost_status == 1){
            cost_id = intent.getString("cost_id").convertInt()
        }
        // 备注
        remark = intent.getString("cost_remark")
        // 图片
        cost_img = intent.getString("cost_img")

        binding.etPriceName.setText(name)
        binding.etPrice.setText(price)
        binding.etInfo.setText(remark)
        val imgList = cost_img.split(",").filter { it.isNotEmpty() }.toMutableList()
        binding.recyclerView.setMediaList(imgList.map { UploadFileBean(url = it) })


    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.titleBar.title = "额外费用"
        binding.titleBar.leftImageView().click { finish() }
        setTabIndex(index, false)
        binding.tvCustomPrice.clickWithTrigger {
            setTabIndex(0, true)
        }
        binding.tvSystemPrice.clickWithTrigger {
            setTabIndex(1, true)
        }

        binding.etPriceName.clickWithTrigger {
            if (binding.tvSystemPrice.isSelected) {
                startPageForResult<ExpenseSelectionActivity>("ids" to order_id) { code, data ->
                    if (code == 88) {
                        if (data != null) {
                            name = data.getStringExtra("name").toString()
                            price = data.getStringExtra("money").toString()
                            cost_id = data.getIntExtra("id", 0)
                            binding.etPriceName.setText(name)
                            binding.etPrice.setText("¥${price}")
                        }
                    }
                }
            }
        }

        binding.tvSave.setOnClickListener {
            val cost_remark = binding.etInfo.text.toString()
            name = binding.etPriceName.text.toString()
            if (index == 0) {
                price = binding.etPrice.text.toString()
                if (name.isEmpty()) {
                    toast("请输入费用名称")
                    return@setOnClickListener
                }
                if (price.isEmpty()) {
                    toast("请输入金额")
                    return@setOnClickListener
                }
                if (price.convertDouble() <= 0.0){
                    toast("金额不能小于0")
                    return@setOnClickListener
                }
                if(cost_remark.isEmpty()){
                    toast("请输入费用备注")
                    return@setOnClickListener
                }
            } else {
                if (name.isEmpty()) {
                    toast("请选择额外费用")
                    return@setOnClickListener
                }
            }

            val imageList = binding.recyclerView.getMediaList().joinToString(","){it.url.toString()}

            if (binding.recyclerView.getMediaList().isEmpty()) {
                toast("请选择照片")
                return@setOnClickListener
            }

            if (index == 0) {
                // 自定义价格
                if (type == 0) {
                    val intt = Intent()

                    intt.putExtra("cost_remark", cost_remark)
                    intt.putExtra(
                        "cost_img",
                        imageList
                    )
                    intt.putExtra("cost_name", name)
                    intt.putExtra("imageList", imageList)
                    intt.putExtra("money", price)
                    setResult(978, intt)
                    finish()
                } else {
                    vm.getData(
                        "id" to order_id,
                        "money" to price,
                        "cost_remark" to cost_remark,
                        "cost_status" to 2,
                        "cost_img" to imageList,
                        "cost_name" to name
                    )
                }
            } else {
                // 平台设定
                if (type == 0) {
                    val intt = Intent()
                    intt.putExtra("cost_img", imageList)
                    intt.putExtra("cost_name", name)
                    intt.putExtra("money", price)
                    intt.putExtra("cost_id", cost_id)
                    setResult(998, intt)
                    finish()
                } else {
                    vm.getData(
                        "id" to order_id,
                        "money" to price,
                        "cost_status" to 1,
                        "cost_img" to imageList,
                        "cost_name" to name
                    )
                }
            }

        }

    }

    private fun setTabIndex(index: Int, clear: Boolean) {
        this.index = index
        binding.tvCustomPrice.isSelected = index == 0
        binding.tvCustomPrice.isBold = index == 0
        binding.tvSystemPrice.isSelected = index == 1
        binding.tvSystemPrice.isBold = index == 1

        binding.etPriceName.isFocusable = index == 0
        binding.etPriceName.isFocusableInTouchMode = index == 0
        binding.etPriceName.hint = if (index == 0) "请输入费用名称" else "请选择"

        binding.ivMore.visibleOrGone(index == 1)

        binding.etPrice.isFocusable = index == 0
        binding.etPrice.isFocusableInTouchMode = index == 0
        binding.etPrice.hint = if (index == 0) "请输入金额" else ""
        binding.llInfo.visibleOrGone(index == 0)
        if (clear) {
            binding.etPrice.setText("")
            binding.etInfo.setText("")
            binding.recyclerView.setMediaList(emptyList())
            binding.etPriceName.setText("")
        }
    }

    override fun initData() {

    }

    override fun startObserve() {
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                toast("提交成功")
                // 打开二维码支付页面
                startPage<ExtraCostsPayActivity>(
                    "orderId" to order_id.toString(),
                    "payName" to binding.etPriceName.text.toString()
                )
                finish()
            }
        }
    }

}